/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ads.tools;

import java.util.ArrayList;

/**
 *
 * @author framet
 */
public class BracketTester {

    public static boolean areBracketsClosed(String text) {
        try {
            checkBrackets(text);
            return true;
        } catch (NotClosedException ex) {
            return false;
        }
    }

    private static void checkBrackets(String stringToCheck) throws NotClosedException {
        ArrayList<String> openedBrackets = new ArrayList<>();
        for (int i = 0; i < stringToCheck.length(); i++) {
            String activeSymbol = stringToCheck.substring(i, i + 1);
            if (activeSymbol.matches("[\\(\\{\\[]")) {
                openedBrackets.add(activeSymbol);
            } else if (activeSymbol.matches("[\\)\\}\\]]")) {
                if (openedBrackets.isEmpty()) {
                    throw new NotClosedException();
                }
                switch (openedBrackets.get(openedBrackets.size() - 1)) {
                    case "(":
                        compareRemove(openedBrackets, activeSymbol, ")");
                        break;
                    case "{":
                        compareRemove(openedBrackets, activeSymbol, "}");
                        break;
                    case "[":
                        compareRemove(openedBrackets, activeSymbol, "]");
                        break;
                }
            }
        }
        if (!openedBrackets.isEmpty()) {
            throw new NotClosedException();
        }
    }

    private static void compareRemove(ArrayList<String> openedBrackets, String selectedBracket, String bracket) throws NotClosedException {
        if (selectedBracket.equals(bracket)) {
            openedBrackets.remove(openedBrackets.size() - 1);
        } else {
            throw new NotClosedException();
        }
    }

    private static class NotClosedException extends Exception {

        public NotClosedException() {
        }
    }
}
